/*
 * Copyright 2002-2020 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.transaction.interceptor;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.aop.support.AopUtils;
import org.springframework.context.EmbeddedValueResolverAware;
import org.springframework.core.MethodClassKey;
import org.springframework.lang.Nullable;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringValueResolver;

/**
 * Abstract implementation of {@link TransactionAttributeSource} that caches
 * attributes for methods and implements a fallback policy: 1. specific target
 * method; 2. target class; 3. declaring method; 4. declaring class/interface.
 *
 * <p>Defaults to using the target class's transaction attribute if none is
 * associated with the target method. Any transaction attribute associated with
 * the target method completely overrides a class transaction attribute.
 * If none found on the target class, the interface that the invoked method
 * has been called through (in case of a JDK proxy) will be checked.
 *
 * <p>This implementation caches attributes by method after they are first used.
 * If it is ever desirable to allow dynamic changing of transaction attributes
 * (which is very unlikely), caching could be made configurable. Caching is
 * desirable because of the cost of evaluating rollback rules.
 *
 * @author Rod Johnson
 * @author Juergen Hoeller
 * @since 1.1
 */
public abstract class AbstractFallbackTransactionAttributeSource
		implements TransactionAttributeSource, EmbeddedValueResolverAware {

	/**
	 * Canonical value held in cache to indicate no transaction attribute was
	 * found for this method, and we don't need to look again.
	 */
	@SuppressWarnings("serial")
	private static final TransactionAttribute NULL_TRANSACTION_ATTRIBUTE = new DefaultTransactionAttribute() {
		@Override
		public String toString() {
			return "null";
		}
	};


	/**
	 * Logger available to subclasses.
	 * <p>As this base class is not marked Serializable, the logger will be recreated
	 * after serialization - provided that the concrete subclass is Serializable.
	 */
	protected final Log logger = LogFactory.getLog(getClass());

	@Nullable
	private transient StringValueResolver embeddedValueResolver;

	/**
	 * Cache of TransactionAttributes, keyed by method on a specific target class.
	 * <p>As this base class is not marked Serializable, the cache will be recreated
	 * after serialization - provided that the concrete subclass is Serializable.
	 */
	private final Map<Object, TransactionAttribute> attributeCache = new ConcurrentHashMap<>(1024);


	@Override
	public void setEmbeddedValueResolver(StringValueResolver resolver) {
		this.embeddedValueResolver = resolver;
	}


	/**
	 * 确定此方法调用的事务属性。如果没有找到方法属性，则默认为类的事务属性。
	 */
	@Override
	@Nullable
	// eg: method=UserServiceImpl.queryByName(java.lang.String) targetClass=UserServiceImpl
	public TransactionAttribute getTransactionAttribute(Method method, @Nullable Class<?> targetClass) {
		if (method.getDeclaringClass() == Object.class) return null;

		/**【步骤1】试图从缓存中取值 */
		Object cacheKey = getCacheKey(method, targetClass);
		TransactionAttribute cached = this.attributeCache.get(cacheKey);
		// eg: cached=null
		if (cached != null)
			if (cached == NULL_TRANSACTION_ATTRIBUTE) return null;
			else return cached;

		/**【步骤2】如果缓存中不存在，则进行解析操作，并维护到缓存中 */
		else {
			// eg: method=UserServiceImpl.queryByName(java.lang.String) targetClass=UserServiceImpl
			TransactionAttribute txAttr = computeTransactionAttribute(method, targetClass); // 提取事务标签
			if (txAttr == null) this.attributeCache.put(cacheKey, NULL_TRANSACTION_ATTRIBUTE); // 维护缓存
			else {
				String methodIdentification = ClassUtils.getQualifiedMethodName(method, targetClass); // 获得方法全路径名
				if (txAttr instanceof DefaultTransactionAttribute) {
					DefaultTransactionAttribute dta = (DefaultTransactionAttribute) txAttr;
					dta.setDescriptor(methodIdentification);
					dta.resolveAttributeStrings(this.embeddedValueResolver);
				}
				this.attributeCache.put(cacheKey, txAttr); // 维护缓存
			}
			return txAttr;
		}
	}

	/**
	 * Determine a cache key for the given method and target class.
	 * <p>Must not produce same key for overloaded methods.
	 * Must produce same key for different instances of the same method.
	 * @param method the method (never {@code null})
	 * @param targetClass the target class (may be {@code null})
	 * @return the cache key (never {@code null})
	 */
	protected Object getCacheKey(Method method, @Nullable Class<?> targetClass) {
		return new MethodClassKey(method, targetClass);
	}

	/**
	 * 真的方法或者类上，提取事务标签
	 * mothod：代表接口中的方法；
	 * specificMethod：代表实现类中的方法;
	 */
	// eg:
	// method=public java.util.List com.muse.springbootdemo.tx.UserServiceImpl.queryByName(java.lang.String)
	// targetClass=class com.muse.springbootdemo.tx.UserServiceImpl
	@Nullable
	protected TransactionAttribute computeTransactionAttribute(Method method, @Nullable Class<?> targetClass) {
		/** 如果仅允许public方法，那么对于非public方法则直接返回null */
		if (allowPublicMethodsOnly() && !Modifier.isPublic(method.getModifiers())) return null;

		/** 获得实现类中的方法 */
		Method specificMethod = AopUtils.getMostSpecificMethod(method, targetClass);

		/**【获取方式1】查看方法specificMethod上是否存在声明式事务的注解，如果有则获取返回 */
		// eg: specificMethod=public java.util.List com.muse.springbootdemo.tx.UserServiceImpl.queryByName(java.lang.String)
		TransactionAttribute txAttr = findTransactionAttribute(specificMethod); // eg: AnnotationTransactionAttributeSource
		if (txAttr != null) // eg: txAttr=null
			return txAttr;

		/**【获取方式2】查看specificMethod的类上是否存在声明式事务@Transactional，如果有则获取返回 */
		// eg: clazz=class com.muse.springbootdemo.tx.UserServiceImpl
		txAttr = findTransactionAttribute(specificMethod.getDeclaringClass()); // eg: AnnotationTransactionAttributeSource
		if (txAttr != null && ClassUtils.isUserLevelMethod(method))
			return txAttr; // eg: attr=PROPAGATION_REQUIRED,ISOLATION_DEFAULT

		 /**【获取方式3】如果specificMethod没有匹配上，那我们回过来查看method的方法上或类上是否使用了声明式事务的注解 */
		if (specificMethod != method) {
			txAttr = findTransactionAttribute(method); /** 3-1：查找接口方法 */
			if (txAttr != null) return txAttr;

			txAttr = findTransactionAttribute(method.getDeclaringClass()); /** 3-2：到接口中的类中去寻找 */
			if (txAttr != null && ClassUtils.isUserLevelMethod(method)) return txAttr;
		}

		return null;
	}


	/**
	 * Subclasses need to implement this to return the transaction attribute for the
	 * given class, if any.
	 * @param clazz the class to retrieve the attribute for
	 * @return all transaction attribute associated with this class, or {@code null} if none
	 */
	@Nullable
	protected abstract TransactionAttribute findTransactionAttribute(Class<?> clazz);

	/**
	 * Subclasses need to implement this to return the transaction attribute for the
	 * given method, if any.
	 * @param method the method to retrieve the attribute for
	 * @return all transaction attribute associated with this method, or {@code null} if none
	 */
	@Nullable
	protected abstract TransactionAttribute findTransactionAttribute(Method method);

	/**
	 * Should only public methods be allowed to have transactional semantics?
	 * <p>The default implementation returns {@code false}.
	 */
	protected boolean allowPublicMethodsOnly() {
		return false;
	}

}
